package com.zj.project.common.base

import android.content.Intent
import android.os.Bundle
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import androidx.lifecycle.ViewModelProvider
import com.jaeger.library.StatusBarUtil
import com.zj.project.common.utils.ActivityUtils
import java.lang.reflect.ParameterizedType
import java.lang.reflect.Type

/**
 * createTime:2021/7/26 15:14
 * auth:张继
 * des:
 */
abstract class BaseActivity<VDB : ViewDataBinding, VM : BaseViewModel> : AppCompatActivity(),
    IBaseView<VM> {
    protected lateinit var binding: VDB
    protected val viewModel: VM by lazy {
        createViewModel()
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        // activity管理
        ActivityUtils.pushActivity(this)
        // 根布局
        binding = DataBindingUtil.setContentView(this, layoutId())
        binding.setVariable(variableId(), viewModel)
        // 添加生命周期
        lifecycle.addObserver(viewModel)
        // 是否是沉浸式
        if (isTranslucent()) {
            StatusBarUtil.setTranslucentForImageView(this, 0, null)
            StatusBarUtil.setLightMode(this)
        }
        initData(savedInstanceState)

        viewModel.startActivityEvent.observe(this) {
            val activity = it["activity"]
            val bundle = it["bundle"]
            startActivity(cls = activity as Class<*>?, bundle = bundle as Bundle?)
        }
        // 错误信息提示
        viewModel.errorMessage.observe(this){
            Toast.makeText(this, it, Toast.LENGTH_SHORT).show()
        }
    }

    private fun startActivity(cls: Class<*>?, bundle: Bundle?) {
        val intent = Intent(this, cls)
        if (bundle != null) {
            intent.putExtras(bundle)
        }
        startActivity(intent)
    }

    override fun isTranslucent(): Boolean {
        return true
    }

    override fun createViewModel(): VM {
        return obtainViewModel(getVMClass())
    }

    private fun getVMClass(): Class<VM> {
        var javaClass: Class<*> = javaClass
        var vmClass: Class<VM>? = null
        while (vmClass == null && javaClass != null) {
            vmClass = getVMClass(javaClass)
            javaClass = javaClass.superclass
        }
        if (vmClass == null) {
            vmClass = BaseViewModel::class.java as Class<VM>
        }

        return vmClass
    }

    private fun getVMClass(cls: Class<*>): Class<VM>? {
        val type = cls.genericSuperclass
        if (type is ParameterizedType) {
            val types: Array<Type> = type.actualTypeArguments
            types.forEach {
                if (it is Class<*>) {
                    if (BaseViewModel::class.java.isAssignableFrom(it)) {
                        return it as Class<VM>
                    }
                } else if (it is ParameterizedType) {
                    val rawType: Type = it.rawType
                    if (rawType is Class<*>) {
                        if (BaseViewModel::class.java.isAssignableFrom(rawType)) {
                            return rawType as Class<VM>
                        }
                    }
                }
            }
        }
        return null
    }

    /**
     * 绑定ViewModel
     */
    private fun obtainViewModel(vmClass: Class<VM>): VM {
        return createViewModelProvider().get(vmClass)
    }

    /**
     * 创建ViewModelProvider实例对象
     */
    private fun createViewModelProvider(): ViewModelProvider {
        return ViewModelProvider(
            this,
            ViewModelProvider.AndroidViewModelFactory.getInstance(this.application)
        )
    }

    override fun onDestroy() {
        ActivityUtils.pop()
        lifecycle.removeObserver(viewModel)
        binding.unbind()
        super.onDestroy()
    }
}